#include <arch/types.h>
#include <kernel/Memory.h>
#include <bitset>

class Memory Memory;

Memory::Memory() {
	for (int i = 256; i < 0x1000; i++) {
		bitmap.set(i, true);
	}

	bitmap.set(0, true);
}

dword Memory::Alloc(dword start, dword frames) {
	dword c, frame, i;
	Lock.Lock();

	while (1) {
		frame = bitmap.first_free(start) * 0x1000;
		if (!frame) {
			Lock.Lock();
			return 0;
		}
		c = frames;
		i = frame;

		while (c) {
			if (bitmap.test(i / 0x1000))
				break;
			c--;
			i += 0x1000;
		}

		if (!c) {
			for (i = 0; i < frames; i++) {
				bitmap.set(i + frame / 0x1000, true);
			}
			Lock.Unlock();
			return frame;
		}
	}
	Lock.Unlock();
	return 0;
}

void Memory::Free(dword start, dword frames) {
	dword i;
	Lock.Lock();
	for (i = 0; i < frames; i++)
		bitmap.reset(start / 0x1000 + i);
	Lock.Unlock();
}

